#include <iostream>

using std::cout;
using std::endl;

class Data
{
public:
    Data(int data = 10)
    : _data(data)
    {
        cout << "Data(int = 10)" << endl;
    }

    int getData() const
    {
        return _data;
    }

    ~Data()
    {
        cout << "~Data()" << endl;
    }
private:
    int _data;
};

class SecondLayer
{
public:
    SecondLayer(Data *pdata)
    : _pdata(pdata)
    {
        cout << "SecondLayer(Data *)" << endl;
    }

    //重载的箭头访问运算符
    Data *operator->()
    {
        return _pdata;
    }

    ~SecondLayer()
    {
        cout << "~SecondLayer()" << endl;
        //认为数据成员指针是new出来
        if(_pdata)
        {
            delete  _pdata;
            _pdata = nullptr;
        }
    }
private:
    Data *_pdata;
};

class ThirdLayer
{
public:
    ThirdLayer(SecondLayer *psl)
    : _psl(psl)
    {
        cout << "ThirdLayer(SecondLayer *)" << endl;
    }

    SecondLayer &operator->()
    {
        return *_psl;
    }

    ~ThirdLayer()
    {
        cout << "~ThirdLayer()" << endl;
        if(_psl)
        {
            delete _psl;
            _psl = nullptr;
        }
    }
private:
    SecondLayer *_psl;
};

void test()
{
    ThirdLayer tl(new SecondLayer(new Data(30)));
    /* tl.operator->().operator->()->getData();//原版形式 */
    cout << "tl->getData() = " << tl->getData() << endl;//简写形式
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

